/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-07-15     MBW       the first version
 */
#include "us016.h"
#include "maths.h"
#include "filter.h"
#include "uart_data.h"
#include "data_define.h"
#include "main.h"
#include "delay_uil.h"
void us016_task(void *p)
{
    u16 cnt = 0;
    u32 t_now,t_preiod,t_pre ;
    void *delay;
    delay = delay_until_create("delay");  // 创建相对延时
    while(1)
    {
        cnt++;
        if(cnt>20)//200Hz读取电池电压
        {
            control_data.batter_vol = Get_batter_Adc_Average(0,10);
            cnt = 0;
        }
        //**********任务运行时间统计**********
        t_now = rt_tick_get();//要赋值给整型数据
        t_preiod=t_now-t_pre;
        task_time1.us016_time = 1000/t_preiod;
        t_pre = t_now;
  //        rt_thread_mdelay(5);
        delay_until_run(delay, 10);
    }
}
void US016_task_init(void)
{
    rt_thread_t tid1 = RT_NULL;
    tid1 = rt_thread_create("us016_task",us016_task, RT_NULL, 2000,us016_task_prio, 20);
    if (tid1 != RT_NULL)rt_thread_startup(tid1),rt_kprintf("...us016_task is ok!\n");
}
INIT_APP_EXPORT(US016_task_init);
u16 Get_Adc(u32 ch)
{
    ADC_ChannelConfTypeDef ADC1_ChanConf;

    ADC1_ChanConf.Channel=ch;                                   //ͨ��
    ADC1_ChanConf.Rank=1;                                       //��1�����У�����1
    ADC1_ChanConf.SamplingTime=ADC_SAMPLETIME_480CYCLES;        //����ʱ��
    ADC1_ChanConf.Offset=0;
    HAL_ADC_ConfigChannel(&hadc1,&ADC1_ChanConf);        //ͨ������

    HAL_ADC_Start(&hadc1);                               //����ADC

    HAL_ADC_PollForConversion(&hadc1,10);                //��ѯת��

    return (u16)HAL_ADC_GetValue(&hadc1);            //�������һ��ADC1�������ת�����
}
//��ȡָ��ͨ����ת��ֵ��ȡtimes��,Ȼ��ƽ��
//times:��ȡ����
//����ֵ:ͨ��ch��times��ת�����ƽ��ֵ
float Get_US016_Adc_Average(u32 ch,u8 times)
{
     u32 temp_val=0;
    u8 t;
    float res=0;
    for(t=0;t<times;t++)
    {
        temp_val+=Get_Adc(ch);
        rt_hw_us_delay(20);
    }
    res =(float) temp_val/times;
    res = res*0.08333-0.41666;
    return res;
}
float Get_batter_Adc_Average(u32 ch,u8 times)
{
     u32 temp_val=0;
    u8 t;
    float res=0;
    for(t=0;t<times;t++)
    {
        temp_val+=Get_Adc(ch);
        rt_hw_us_delay(20);
    }
    res =(float) temp_val/times;
    res = res*11*3.3/4096;
    return res;
}
